package util;
/**
 * 
 * @author Himadri
 */
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import model.Preference;
import model.Settings;
import platform.Platform;
import player.Test;

public class EmailSending {
	public static EmailSending _instance;
	private Properties props;
	private Message message;
	private static final String className = Test.class.getName();
	
	private EmailSending()
	{
		props = new Properties();
		props.put("mail.smtp.host", Settings.SMTP_HOST);
		props.put("mail.smtp.socketFactory.port", Settings.SMTP_PORT);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", Settings.SMTP_PORT);
		props.setProperty("mail.pop3.connectionpooltimeout", "3000");
		props.setProperty("mail.pop3.connectiontimeout", "3000");
		props.setProperty("mail.pop3.timeout", "3000");
	}
	
	public static String FormatException(Throwable throwable) {
		String string = "";
		if(throwable != null)
		{
			StringWriter sw = new StringWriter();
	        PrintWriter pw = new PrintWriter(sw, true);
	        throwable.printStackTrace(pw);
	        pw.flush();
	        sw.flush();
	        string = sw.toString();
		}
		return string;
	}
	
	public static String ProcessEmailBody(String IncidentReason,String IncidentMessage,String IncdientError)
	{
		String IncidentAt = "\n\nTime: = "+new Date().toString();
		String platform = "\n\nPatform: = "+Platform.getPlatform().toString();
		IncdientError = "\n\nError: = "+IncdientError;
		IncidentReason = "\n\nReason: = "+IncidentReason;
		IncidentMessage = "\n\nComment: = "+IncidentMessage;
		String logenabled = (Preference.getInstance().isCheckLogging()) ? "\n\nLogging: = Enabled":"\n\nLogging: = Disabled";
		String Version = "\n\n\nVersion: = "+String.valueOf(Settings.VERSION);
		
		//String Signature = "\n\n\n\n\nRegards,\nDMB Player Team\n";
		String EBody = Version+IncidentAt+IncdientError+IncidentReason+IncidentMessage+platform+logenabled;
		return EBody;
	}
	
	public static EmailSending getInstance()
	{
		if(_instance == null)
		{
			_instance = new EmailSending();
		}
		return _instance;
	}
	
	public boolean send(String ToAdress, String Subject, String Body)
	{
		
		if(!Preference.getInstance().isEheckEmailSending())
		{
			System.out.println("EMAIL IS DISABLED");
			return false;
		}
		
		if (!PlayerUtilities.hasNetworkConnection()) {
			LoggingUtils.log(Level.SEVERE, "NO Network Connection to, Can not send email");
			return false; // if no network, do nothing
		}
		
		if(Preference.getInstance().getBoxID() == 0)
			return false;
		
		if(!Preference.getInstance().isCheckUpdates())
			return false;
		
		final String classMethod = className + " send(String ToAdress, String Subject, String Body) ";
		LoggingUtils.logStart(classMethod);
		
		boolean isent = false;
		try {
			Session session = authenticate(); 
			message = new MimeMessage(session);
			message.setSentDate(new Date());
			message.setFrom(new InternetAddress(Settings.From_USER));
			//message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("rakesh@digitalmenubox.com"));
			message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(ToAdress));
			message.setSubject(Subject);
			message.setText(Body);
			
			Transport.send(message);
			isent = true;
		}
		catch(MessagingException e){
			LoggingUtils.log(Level.SEVERE, "Email sending problem " + classMethod, e);
			//e.printStackTrace();
		}
		catch(Exception e){
			LoggingUtils.log(Level.SEVERE, "Email sending problem " + classMethod, e);
			//e.printStackTrace();
		}
		return isent;
	}
	
	private Session authenticate()
	{
		Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(Settings.SMTP_USER,Settings.SMTP_PASSWORD);
					}
				});
		return session;
	}
	public static void main(String[] args) {
		
		//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		
		String Ebody = ProcessEmailBody("Unknown", "Critical", "Null pointer");
		
		if(getInstance().send(Settings.TO_USER,  "Subject Test", Ebody))
		{
			LoggingUtils.log(Level.SEVERE, "Email has been sent" );
		}
		else
		{
			LoggingUtils.log(Level.SEVERE, "Email sending fail" );
		}
		
		System.out.println(new Date().toString());
	}
}
